import numpy as np

array = np.random.rand(4,4)
randMat = np.matrix(array)
invRandMat = randMat.I
myEye = randMat * invRandMat

data = np.array([1,2,3,4])
print(data)

data = np.array([[1,2,3,4],[4,5,6,7]])
print(data)

data = np.zeros(shape=(5,3))  #5行3列
print(data)

data = np.ones(shape=(3,4))
print(data)

data = np.empty(shape=(4,3))
print(data)

data = np.arange(10,16,2) # 元素值范围[10,16), 步长2
print(data) # [10,12,14]

# 创建linspace 线性等分量
data = np.linspace(1,10,20) #开始1，结束10，20等分
print(data)  # 1+(9/19)*i

data = np.random.rand(3,4)
print(data)

data = np.random.randint(2,5,size=(4,5)) #4行5列，元素值范围 [2,5)
print(data)

# reshape, 将数组展成一维，然后重新划分维度。前后元素总数必须相等
data1 = [1,2,3,4,5]
data2 = [6,7,8,9,10]
data = np.array([data1, data2])
print("reshape之前的数组形状为：")
print(data.shape)
print(data)
data = data.reshape((5,2))
print("reshape之后的数组形状为：")
print(data.shape)
print(data)

# 数组转置 T
data = [[1,2,3],[4,5,6],[7,8,9]]
data_array = np.array(data)
print("转置前数组：")
print(data_array)
print("转置后数组：")
print(data_array.T)

# 数组属性查询
data = np.array([1,2,3])
print(data)
print(data.ndim)  # 1
print(data.shape) # (3,)  一维数组3行
print(data.size)  # 3
print(data.dtype) # int64

# 数组的运算
array1 = np.array([1,2,3])
array2 = np.array([4,5,6])
result = array1 + array2
print(result)
result = array1 * array2  # 元素逐个相乘，注意这不是矩阵乘法
print(result)

# 数组中的数据统计
# 平均值 numpy.mean(arr, axis=None, dtype=None, out=None): 
# 计算数组的平均值。
# 参数axis表示沿着哪个轴进行计算，默认为None，表示计算整个数组的平均值；
# dtype表示返回结果的数据类型，默认为float64；
# out表示将结果存储在指定的数组中
data = [[1,3,5,7],[2,4,6,8]]
mindle = np.mean(data, 0) # axis 0 将所有行对应元素进行平均； axis 1 将每行的所有列进行平均
print(mindle)

# 计算中位数
# numpy.median(arr, axis=None, out=None)
data = [1,5,6,9]
data1 = np.median(data)
print(data1)

# 标准差
print(np.std(data))

# 方差
print(np.var(data))

# min,max
print(np.min(data))
print(np.max(data))

# sum
print(np.sum(data))

# 乘积
print(np.prod(data))

# 累积和
print(np.cumsum(data))  #[1,6,12,21]

# 切片
# 切片范围是左闭右开,索引从0开始
arr = np.array([1,2,3,4,5])
print(arr[1:4]) # [2,3,4]

# 堆叠
array1 = np.array([1,2,3,4,5])
array2 = np.array([6,7,8,9,0])
stacked_vertically = np.vstack((array1, array2))
print(stacked_vertically)
stacked_horizontally = np.hstack((array1, array2))
print(stacked_horizontally)

# 保存和加载数组
np.save('my_array.npy', stacked_vertically)
loaded_data = np.load('my_array.npy')
print(loaded_data)